package cn.edu.sdu.sol.material_management_system.service;

import cn.edu.sdu.sol.material_management_system.model.po.Room;
import cn.edu.sdu.sol.material_management_system.model.po.User;
import cn.edu.sdu.sol.material_management_system.model.vo.DataRequest;
import cn.edu.sdu.sol.material_management_system.model.vo.DataResponse;
import cn.edu.sdu.sol.material_management_system.repository.RoomRepository;
import cn.edu.sdu.sol.material_management_system.repository.UserRepository;
import cn.edu.sdu.sol.material_management_system.utils.JwtUtil;
import cn.edu.sdu.sol.material_management_system.utils.VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class RoomService {
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    RoomRepository roomRepository;

    @Autowired
    UserRepository userRepository;

    VO vo = new VO();

    public DataResponse getRoomNum(String token) {
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<User> sysUser = userRepository.findUserByStudentNum(studentNum);
        assert sysUser.isPresent();
        return vo.data(roomRepository.countRooms());
    }

    public DataResponse addRoom(DataRequest req, String token) {
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<User> user = userRepository.findUserByStudentNum(studentNum);
        assert user.isPresent();
        User u = user.get();
        String name = req.getString("name");
        String introduction = req.getString("name");
        Room room = new Room(null, name, introduction, u);
        roomRepository.save(room);
        return vo.ok();
    }
}
